package com.liu.juc.product;

/**
 * @author TOP_LIU
 * @description 生产者和消费者
 * @date 2021/9/16
 */
public class ProductConsumer {
    public static void main(String[] args) {

        Person p = new Person();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    p.increament();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    p.decreament();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    p.increament();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    p.decreament();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "D").start();


    }
}

class Person {
    private int count = 0;

    //加一操作
    public synchronized void increament() throws InterruptedException {
        while (count > 0) {
            //等待
            this.wait();
        }
        count++;
        // 释放锁
        this.notifyAll();
        System.out.println(Thread.currentThread().getName() + "=>" + count);
    }

    //减一操作
    public synchronized void decreament() throws InterruptedException {
        while (count == 0) {
            //等待
            this.wait();
        }
        count--;
        // 释放锁
        this.notifyAll();
        System.out.println(Thread.currentThread().getName() + "=>" + count);
    }


}
